package com.jrzh.mvc.service.sys.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jrzh.common.exception.ProjectException;
import com.jrzh.framework.I18nHelper;
import com.jrzh.framework.base.convert.BaseConvertI;
import com.jrzh.framework.base.repository.BaseRepository;
import com.jrzh.framework.base.service.impl.BaseServiceImpl;
import com.jrzh.framework.bean.SessionUser;
import com.jrzh.mvc.convert.sys.RoleConvert;
import com.jrzh.mvc.model.sys.ResourcesModel;
import com.jrzh.mvc.model.sys.RoleModel;
import com.jrzh.mvc.repository.sys.RoleRepository;
import com.jrzh.mvc.search.sys.RoleSearch;
import com.jrzh.mvc.service.sys.ResourcesServiceI;
import com.jrzh.mvc.service.sys.RoleServiceI;
import com.jrzh.mvc.view.sys.ResourcesView;
import com.jrzh.mvc.view.sys.RoleView;

@Service("roleService")
public class RoleServiceImpl extends BaseServiceImpl<RoleModel, RoleSearch, RoleView> implements RoleServiceI{
	@Autowired
	private RoleRepository roleRepository;
	
	@Autowired
	private ResourcesServiceI resourcesService;
	
	@Autowired
	private RoleConvert roleConvert;
	
	@Override
	public BaseConvertI<RoleModel, RoleView> getConvert() {
		return roleConvert;
	}

	@Override
	public BaseRepository<RoleModel, Serializable> getDao() {
		return roleRepository;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
	public void saveResources(RoleView view, SessionUser user) throws ProjectException {
		RoleModel role = this.findById(view.getId());
		if(null == role) throw new ProjectException(I18nHelper.getI18nByKey("message.object_not_null", user));
		List<ResourcesModel> resourceList = new ArrayList<ResourcesModel>();
		if(null != view.getResourceIds() || view.getResourceIds().length > 0) {
			resourceList = resourcesService.listInByField("id", view.getResourceIds());
		}
		role.setResources(resourceList);
		this.edit(role, user);
	}

	@Override
	public List<ResourcesView> loadResources(Serializable id) throws ProjectException {
		RoleModel role = this.findById(id);
		if(null == role) throw new ProjectException(I18nHelper.getI18nByKey("message.object_not_null", new SessionUser()));
		return resourcesService.convertByModelList(role.getResources());
	}


}
